/*
 * Copyright (C) 2013 Daniel Wasilew <daniel.wasilew@codeminer.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.codeminer.parts.server.permissions;

import org.codeminer.database.DatabaseException;
import org.codeminer.database.DatabaseManager;
import org.codeminer.parts.application.ApplicationComponent;
import org.codeminer.parts.application.ApplicationContext;
import org.codeminer.parts.application.ShutdownCallback;
import org.codeminer.parts.database.PermissionsConnector;
import org.codeminer.parts.server.users.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.EnumSet;
import java.util.Set;

/**
 * @author Daniel Wasilew <daniel.wasilew@codeminer.org>
 */
public class DefaultPermissionManager implements PermissionManager, ApplicationComponent {

    private static final Logger log = LoggerFactory.getLogger(DefaultPermissionManager.class);
    private ApplicationContext applicationContext;

    @Override
    public void shutdown() {
    }

    @Override
    public void startup(ApplicationContext context, ShutdownCallback shutdownCallback) throws Exception {
        this.applicationContext = context;
    }

    @Override
    public Set<Permission> getPermissions(User user) {
        try {
            return getStorageConnector().get(user);
        } catch (DatabaseException ex) {
            log.error("could not fetch permissions", ex);
            return Collections.emptySet();
        }
    }

    @Override
    public void setPermissions(User user, Set<Permission> permission) {
        if (user == null || permission == null) {
            throw new IllegalArgumentException("user or permissions == null");
        }
        try {
            getStorageConnector().setPermissions(user, permission);
        } catch (DatabaseException ex) {
            log.error("could not store permissions", ex);
        }
    }

    private PermissionsConnector getStorageConnector() throws DatabaseException {
        return applicationContext.getApplicationPart(DatabaseManager.class).getConnector(PermissionsConnector.class);
    }

    @Override
    public void removePermission(User user, Permission permission) {
        try {
            getStorageConnector().removePermission(user, permission);
        } catch (DatabaseException ex) {
            log.error("could not store permissions", ex);
        }
    }

    @Override
    public void addPermission(User user, Permission permission) {
        if (user == null || permission == null) {
            throw new IllegalArgumentException("user or permission is null");
        }
        Set<Permission> current = getPermissions(user);
        current.add(permission);
        try {
            getStorageConnector().setPermissions(user, current);
        } catch (DatabaseException ex) {
            log.error("could not store permissions", ex);
        }
    }

    @Override
    public Set<Permission> granted(User user, Set<Permission> requestedPermissions) {
        try {
            Set<Permission> notGranted = EnumSet.copyOf(requestedPermissions);
            if (user == null) {
                return notGranted;
            }
            Set<Permission> current = getStorageConnector().get(user);
            if (current == null) {
                return notGranted;
            } else {
                for (Permission permission : current) {
                    if (permission == Permission.ALL) {
                        return EnumSet.noneOf(Permission.class);
                    }

                    notGranted.remove(permission);
                }
                return notGranted;
            }
        } catch (DatabaseException ex) {
            log.error("could not get permissions", ex);
            return EnumSet.allOf(Permission.class);
        }
    }

    @Override
    public Class getDescriptionClass() {
        return PermissionManager.class;
    }
}
